package com.yang.edu;


import com.yang.po.Orders;

import java.awt.*;
import java.sql.*;

/**
 * @Description: SQL语句的执行器, 这里负责调用数据库
 * @author: Yang Qiang
 * @create: 2021-11-09 21:09
 */
public class YangExecutor {
    // 连接数据库需要的参数
    private static final String URL = "jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8";
    private static final String USER_NAME = "root";
    private static final String PASS_WORD = "root";


    /**
     * 执行SQL语句
     *
     * @param sql
     * @return
     */
    public Object selectById(String sql, Object args){
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        Orders orders = new Orders();

        try {
            //1 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2 获取链接
            connection = DriverManager.getConnection(URL, USER_NAME, PASS_WORD);
            //3 创建语句并执行
            statement = connection.createStatement();
            String sqlInfo = String.format(sql, args);
            resultSet = statement.executeQuery(sqlInfo);
            //4 把得到的结果转换为实体类
            while (resultSet.next()) {
                Integer id = resultSet.getInt("id");
                Integer amount = resultSet.getInt("amount");
                Integer user_id = resultSet.getInt("user_id");
                orders.setId(id);
                orders.setAmount(amount);
                orders.setUser_id(user_id);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                connection.close();
                resultSet.close();
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        return orders;
    }
}
